package myJs.common.changePassword

import myJs.CpLayer
import myJs.cps.{PureInputCp, Style}
import myJs.myPkg.jquery.$
import org.scalajs.dom.html
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.core.facade.React
import slinky.web.html._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import myJs.Implicits._
import myJs.api.Api
import myJs.common.InputInlinePasswordCp
import myJs.myPkg.reactHookForm._
import myJs.myPkg.{MyFetch, NavigateOptions, ReactRouterDOM}
import myJs.tool.Tool
import org.scalajs.dom.window.localStorage
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.ChangePassword

import scala.scalajs.js.{JSON, |}

/**
 * Created by yz on 21/1/2022
 */
@react object Cp {

  val curPage = ChangePasswordP
  type Props = Unit

  val component = FunctionalComponent[Props] { props =>

    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))
    val (info, setInfo) = useState("")
    val (password, setPassword) = useState("")
    val (newPassword, setNewPassword) = useState("")
    val (newPasswordAgain, setNewPasswordAgain) = useState("")
    val navigate = ReactRouterDOM.useNavigate()

    object FTool {

      def passwordChange = (v: String) => {
        setPassword(v)
      }

      def newPasswordChange = (v: String) => {
        setNewPassword(v)
      }

      def newPasswordAgainChange = (v: String) => {
        setNewPasswordAgain(v)
      }

      def changePassword = () => {
          val account = Tool.getAccount
          val request = ChangePassword.Request(account = account, password = password, newPassword = newPassword)
          Api.changePassword(request).map { response =>
            if (response.valid) {
              navigate("/", options = NavigateOptions(state = js.Dictionary("message" -> "密码修改成功！")))
            } else {
              setInfo("密码错误！")
            }
          }
        ()
      }

      def formSubmit = useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.changePassword()
      })

      def newPasswordAgainSameValidate = (v: String) => {
        val rs = if (v != newPassword) {
          "两次密码不一样!"
        } else true
        rs.asInstanceOf[Boolean | String]
      }

    }

    useEffect(() => {
      if (newPassword.nonBlank) {
        useForm.trigger("newPasswordAgain")
      }
    }, List(newPassword)
    )

    CpLayer(title = curPage.titleStr)(
      div(className := "page-content",
        div(className := "row-fluid",
          div(className := "row",
            div(className := "col-md-12 col-sm-12",
              div(className := "portlet light",
                div(className := "portlet-body",

                  div(className := "register",
                    div(className := "page-heading",
                      h2(className := "col-sm-offset-1", style := Style(fontSize = "25px"), "修改密码")
                    ),
                    form(className := "registration-form form-horizontal", onSubmit := FTool.formSubmit,
                      style := Style(marginTop = "30px"),

                      div(className := "col-sm-offset-5",
                        span(style := Style(lineHeight = "35px"), className := "error", info),
                      ),

                      InputInlinePasswordCp(useForm = useForm, label = "旧密码", name = "password",
                        value = password, onChange = FTool.passwordChange, placeHolder = "旧密码",
                        registerOptions = RegisterOptions(
                          required = ValidationValueMessage(value = true, message = "密码不能为空！")
                        )
                      ),

                      InputInlinePasswordCp(useForm = useForm, label = "新密码", name = "newPassword",
                        value = newPassword, onChange = FTool.newPasswordChange, placeHolder = "新密码",
                        registerOptions = RegisterOptions(
                          required = ValidationValueMessage(value = true, message = "新密码不能为空！"),
                        )
                      ),

                      InputInlinePasswordCp(useForm = useForm, label = "再次确认新密码", name = "newPasswordAgain",
                        value = newPasswordAgain, onChange = FTool.newPasswordAgainChange, placeHolder = "再次确认新密码",
                        registerOptions = RegisterOptions(
                          required = ValidationValueMessage(value = true, message = "确认密码不能为空！"),
                          validate = FTool.newPasswordAgainSameValidate
                        )
                      ),

                      div(className := "form-group",
                        div(className := "actions col-sm-offset-5 col-sm-3",
                          button(`type` := "submit", className := "btn btn-primary btn-lg",
                            style := Style(width = "100%"), "确认修改")
                        )
                      )

                    )
                  )

                ),
              )
            )
          )
        )
      )

    )

  }


}
